package com.bawei.play.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.play.intent.PlayViewIntent
import com.bawei.play.model.PlayVideoRepository
import com.bawei.play.uistate.PlayUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2024/3/4
 * Desc:
 */
@HiltViewModel
class PlayViewModel @Inject constructor(private val repository: PlayVideoRepository): BaseViewModel<PlayViewIntent>(){

    private val _uiState = MutableStateFlow<PlayUiState>(PlayUiState.LoadEmpty)
    val uiState: StateFlow<PlayUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: PlayViewIntent) {
        when(intent){
            is PlayViewIntent.LoadRecommendSimpleVideoList -> loadRecommendSimpleVideoList(intent.page, intent.pageSize)
            is PlayViewIntent.LoadSimpleVideoListById ->loadSimpleVideoById(intent.channelId, intent.page, intent.pageSize)
        }
    }


    private fun loadRecommendSimpleVideoList(page:Int, pageSize: Int) {
        viewModelScope.launch {
            try {
                val (code, data, msg) = repository.getRecommendVideo(page, pageSize)
                Log.i("", "loadRecommendSimpleVideoList:========= ${data.toString()} ")
                if(code == 0 && data.isNotEmpty()){
                    _uiState.value = PlayUiState.LoadSimpleVideoSuccess(data)
                }else{
                    _uiState.value = PlayUiState.LoadSimpleVideoFail(msg)
                }
            } catch (e: Exception){
                _uiState.value = PlayUiState.LoadSimpleVideoFail("网络请求失败！")
            } finally {
                this.cancel()
            }
        }
    }

    private fun loadSimpleVideoById(channelId: String, page:Int, pageSize: Int){
        viewModelScope.launch {
            try {
                val (code, data, msg) = repository.getVideoByChannelId(channelId, page, pageSize)
                Log.i("", "loadSimpleVideoById:========= ${data.toString()} ")
                if(code == 0 && data.isNotEmpty()){
                    _uiState.value = PlayUiState.LoadSimpleVideoSuccess(data)
                }else{
                    _uiState.value = PlayUiState.LoadSimpleVideoFail(msg)
                }
            } catch (e: Exception){
                _uiState.value = PlayUiState.LoadSimpleVideoFail("网络请求失败！")
            } finally {
                this.cancel()
            }
        }

    }



}